<template>
  <el-cascader v-bind="$attrs" v-model="selected" :options="options" ref="cascader" @change="input" :props="props" :show-all-levels="showAllLevels">
  </el-cascader>
</template>
<script>
  import { regionData } from "element-china-area-data";
  export default {
    data() {
      return {
        selected: [], //选择值
        options: regionData  //行政区域选项
      }
    },
    props: ['value','props', 'showAllLevels'],
    mounted() {
        this.init(this.value)
    },
    watch: {
      value(val) {
        this.init(val)
      }
    },
    methods: {
        init (val) {
            // 适配数据导入时用户使用 / 符号来分隔
            if (Array.isArray(val)) {
                if (val.length === 1 && (val[0].indexOf('/') !== -1 || val[0].indexOf(',') !== -1)) {
                    const str = val[0]
                    let keys = str.indexOf('/') !== -1 ? str.split('/') : str.split(',')
                    let codeLst = []
                    let index = 0
                    keys.length > 0 && this.getValueByKey(this.options, keys, index, codeLst)
                    this.selected = [...codeLst]
                } else {
                    this.selected = val
                }
            }
        },
      getValueByKey(options, key, index, str) {
        options && options.length > 0 && options.forEach((item) => {
            if (item.value.toString() === key[index] || item.label === key[index]) {
                str.push(item.value)
                index++
                item?.children && index < key.length && this.getValueByKey(item.children, key, index, str)
                return true
            }
        })
      },
      input(val) {
        this.$emit('input', val)
        this.$emit('change', val)
      }
    }
  }
</script>
